function setCookie (name, value, expires, path, domain, secure) {
      document.cookie = name + "=" + escape(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "");
}
function getCookie(name) {
	var cookie = " " + document.cookie;
	var search = " " + name + "=";
	var setStr = null;
	var offset = 0;
	var end = 0;
	if (cookie.length > 0) {
		offset = cookie.indexOf(search);
		if (offset != -1) {
			offset += search.length;
			end = cookie.indexOf(";", offset)
			if (end == -1) {
				end = cookie.length;
			}
			setStr = unescape(cookie.substring(offset, end));
		}
	}
	return(setStr);
}

var chat = {
	hover: false,
	cur_X: 0,
	cur_Y: 0,
	pos_X: 0,
	pos_Y: 0,
	lastID: 0,
	timer: {
		handler: 0,
		start: function(){
			this.handler = setInterval(chat.check,1500);
		},
		stop: function(){
			clearInterval(this.handler);
		}
	},
	init: function(){
		// инициализация
		var chat_parent = chat;
		// элементы
		$("body").prepend("<div id='chat_hide'>Мини-Чат</div>");
		var html = "\
			<div id='chat'>\
				<div id='chat_head'>\
					<div id='chat_caption'>Мини-Чат</div>\
					<div id='chat_min'>_</div>\
				</div>\
				<div id='chat_list'>\
				</div>\
				<input type='text' id='chat_write' />\
				<input type='button' id='chat_send' value='OK' />\
			</div>";
		$("body").prepend(html);
		// настройка
		/* chat_parent.pos_X = getCookie("chat_pos_X") || 0;
		chat_parent.pos_Y = getCookie("chat_pos_Y") || 0; */
		show = getCookie("chat_show") || "block";
		//$("#chat").css({"top":chat_parent.pos_Y+"px","left":chat_parent.pos_X+"px","display":show});
		$("#chat").css({"display":show});
		if (show == "none")
			$("#chat_hide").fadeIn(0);
		
		// события
		//$("#chat_head").mousedown(function(e){ e.stopPropagation() })							// 
		$("#chat_min").mousedown(function(e){ e.stopPropagation() })							// 
		$("#chat_send").click(function(e){ chat_parent.send(); })									// 
		$("#chat_write").keypress(function(e){ if (e.keyCode == 13) chat_parent.send(); })			// hotkey на Enter
		$("#chat_min").click(function(){ chat_parent.hide(); });										// 
		$("#chat_hide").click(function(){ chat_parent.show(); });									// 
		
		// события перещения
		/* $("#chat_head").mousedown(function(e){
			chat_parent.hover = true;
			chat_parent.cur_X = e.offsetX || e.layerX;
			chat_parent.cur_Y = e.offsetY || e.layerY;
		})
		$(document).mousemove(function(e){
			if (chat_parent.hover)
				$("#chat").css({"top":e.pageY-chat_parent.cur_Y+298,"left":e.pageX-chat_parent.cur_X,"opacity":"0.5"});
		})
		$("#chat_head").mouseup(function(){
			chat_parent.hover = false;
			var left = $("#chat").offset().left + parseInt($(this).css("marginLeft")),
			top = $("#chat").offset().top + parseInt($(this).css("marginTop"));
			$("#chat").css("opacity","1");
			setCookie("chat_pos_X",left,new Date("01 Jan 2015"),"/");
			setCookie("chat_pos_Y",top,new Date("01 Jan 2015"),"/");
			chat_parent.pos_X = left;
			chat_parent.pos_Y = top;
		}) */
		
		// старт
		chat_parent.start();
		chat_parent.timer.start();
	},
	start: function() {
		var chat_parent = chat;
		$.ajax({
			url: "/ajax/chat/start",
			success: function(data){
				chat_parent.lastID = data;
				chat_parent.check();
			}
		})
	},
	check: function() {
		var chat_parent = chat;
		$.ajax({
			url: "/ajax/chat/check?lastid="+chat_parent.lastID,
			success: function(data){
				var response = $.parseJSON(data);
				if (response)
				{
					chat_parent.lastID = response[response.length-1]['id'];
					for (var i = 0; i < response.length; i++)
					{
						var div = "\
						<div class='chat_message_item'>\
							<div class='chat_name'>"+response[i]['user']+" <span class='chat_time'>("+response[i]['time']+")</span>:</div>\
							<div class='chat_message'>"+response[i]['message']+"</div>\
						</div>";
						$("#chat_list").append(div).scrollTo($(".chat_message_item:last"));
					}
				}
			}
		})
	},
	send: function() {
		var chat_parent = chat;
		$.ajax({
			url: "/ajax/chat/send?message="+encodeURIComponent($("#chat_write").val()),
			success: function(data){
				if (data == "success")
					$("#chat_write").val("");
			}
		})
	},
	show: function() {
		$("#chat_hide").fadeOut(0);
		$("#chat").fadeIn(0);
		setCookie("chat_show","block",new Date("01 Jan 2015"),"/");
	},
	hide: function() {
		$("#chat").fadeOut(0);
		$("#chat_hide").fadeIn(0);
		setCookie("chat_show","none",new Date("01 Jan 2015"),"/");
	}
};

$(document).ready(function(){
	chat.init();
})